package com.rainkaze.IntelliDrawNote.utils;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class AiHelperUtils {

    public interface AiCallback {
        void onSuccess(String response);
        void onError(String error);
    }

    // 这里是我自己申请的DeepSeek API Key
    //TODO:增加配置文件，让用户自己填入自己的key
    private static final String API_KEY = "sk-9116752c22784e6dabe2bf3f8fc36678";

    public static void sendRequest(String userMessage, AiCallback callback) {
        new Thread(() -> {
            try {
                URL url = new URL("https://api.deepseek.com/chat/completions");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
                connection.setDoOutput(true);

                // 构建请求体
                //TODO:增加选择框，自由选择是启用R1还是V3模型
                JSONObject payload = new JSONObject();
                payload.put("model", "deepseek-chat");

                JSONArray messages = new JSONArray();
                messages.put(new JSONObject().put("role", "system").put("content", "你是一个笔记助手."));
                messages.put(new JSONObject().put("role", "user").put("content", userMessage));
                payload.put("messages", messages);
                payload.put("stream", false);

                // 写入请求体
                OutputStream os = connection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(payload.toString());
                writer.flush();
                writer.close();
                os.close();

                // 读取响应
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    // 回调到主线程
                    new Handler(Looper.getMainLooper()).post(() -> {
                        callback.onSuccess(response.toString());
                    });
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        callback.onError("响应失败，错误码：" + responseCode);
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
                new Handler(Looper.getMainLooper()).post(() -> {
                    callback.onError("异常：" + e.getMessage());
                });
            }
        }).start();
    }
}
